package hw_7_27;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class Demo1_FileOutputStream {
    public static void main(String[] args) {
        File file = new File("doc/test.txt");
        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            System.out.println("创建新目录成功！");
        }
        try {
            if (!file.exists()) {
                file.createNewFile();
                System.out.println("新的文本文件创建成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(file,true);
            String str = new String("Hello World！");
            fos.write(str.getBytes(StandardCharsets.UTF_8));
            fos.flush();
            System.out.println("写入数据成功！");
            fis = new FileInputStream("doc/test.txt");
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1){
                String text = new String(buffer,0,length);
                System.out.println(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
